<template>
	<view class="login-container">
		<view class="login-form">
			<view class="form-item">
				<text class="label">用户名</text>
				<input type="text" v-model="formData.username" class="input" placeholder="用户名"
					placeholder-class="placeholder" />
			</view>

			<view class="form-item">
				<text class="label">密码</text>
				<input type="password" v-model="formData.password" class="input" placeholder="密码"
					placeholder-class="placeholder" />
			</view>

			<button class="login-btn" @tap="handleLogin">登录</button>

			<view class="register-link" @tap="goToRegister">
				<text>还没有账号？</text>
				<text class="link">立即注册</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { useUserStore } from '@/store';
import { reqLogin, reqGetOpenid } from '@/api/user';
import { onLoad } from '@dcloudio/uni-app';

const userStore = useUserStore();
const from = ref('');

// 监听页面加载
onLoad((options) => {
	from.value = options.from || '';
});

const formData = ref({
	username: '',
	password: ''
});

const handleLogin = async () => {
	if (!formData.value.username || !formData.value.password) {
		uni.showToast({
			title: '请输入用户名和密码',
			icon: 'none'
		});
		return;
	}

	try {
		uni.showLoading({
			title: '登录中...'
		});

		// 调用登录接口
		const res = await reqLogin({
			username: formData.value.username,
			password: formData.value.password
		});

		// 根据实际返回的数据结构处理
		if (res.status === 0) { // status为0表示成功
			// console.log('登录返回数据:', JSON.stringify(res));
			// 存储令牌和用户信息
			userStore.updateToken(res.token, res.refreshToken);
			userStore.updateUserInfo(res.userInfo);

			uni.hideLoading();//
			uni.showToast({
				title: res.message || '登录成功',
				icon: 'success',
				duration: 1500,
				success: () => {
					// 延迟执行返回，确保 Toast 显示完成
					setTimeout(() => {
						if (from.value === 'cart') {
							uni.switchTab({
								url: '/pages/cart/cart'
							});
						} else if (from.value === 'register') {
							uni.switchTab({
								url: '/pages/index/index'
							});
						} else {
							// 返回上一页
							uni.navigateBack();
						}
					}, 1500);
					//条件判断，如果是小程序，就要获取openid,然后存储到本地
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success: async function (loginRes) {
							if (loginRes.code) {
								try {
									const res = await reqGetOpenid(loginRes.code);
									console.log('res', res);
									if (res.openid) {
										// 存储openid到本地
										uni.setStorageSync('openid', res.openid);
										console.log('openid存储成功');
									}
								} catch (error) {
									console.error('获取openid失败：', error);
								}
							} else {
								console.error('登录失败：' + loginRes.errMsg);
							}
						},
						fail: function (err) {
							console.error('微信登录失败：', err);
						}
					});
					// #endif
				}
			});
		} else {
			uni.hideLoading();
			uni.showToast({
				title: res.message || '登录失败',
				icon: 'error'
			});
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			title: error.message || '登录失败',
			icon: 'error'
		});
	}
};

// 跳转到注册页面
const goToRegister = () => {
	uni.navigateTo({
		url: '/pages/user_package/register/register'
	});
};
</script>

<style lang="scss" scoped>
.login-container {
	min-height: 100vh;
	padding: 40rpx;
	background-color: #fff;

	.login-form {
		margin-top: 60rpx;

		.form-item {
			margin-bottom: 40rpx;

			.label {
				display: block;
				font-size: 32rpx;
				color: #333;
				margin-bottom: 20rpx;
			}

			.input {
				width: 100%;
				height: 88rpx;
				padding: 0 20rpx;
				font-size: 30rpx;
				color: #333;
				border-bottom: 2rpx solid #eee;
				transition: border-color 0.3s ease;

				&:focus {
					border-color: #2196f3;
				}
			}

			.placeholder {
				color: #999;
			}
		}

		.login-btn {
			width: 100%;
			height: 88rpx;
			line-height: 88rpx;
			margin-top: 60rpx;
			background: #2196f3;
			color: #fff;
			font-size: 32rpx;
			border-radius: 44rpx;
			border: none;

			&:active {
				opacity: 0.9;
			}

			&::after {
				border: none;
			}
		}

		.register-link {
			margin-top: 40rpx;
			text-align: center;
			font-size: 28rpx;
			color: #666;

			.link {
				color: #2196f3;
				margin-left: 10rpx;
			}
		}
	}
}
</style>
